﻿using System;
using System.ComponentModel;

/// <summary>
/// 释放对象的基类
/// </summary>
public class PDispose : IDisposable
{    
    // 一个对象的句柄
    private IntPtr handle;    
    // 应用程序间的对象共享
    private Component Components = new Component();
    // 是否执行过释放处理
    private bool disposed = false;
    
    public PDispose()
    {
        
    }

    public PDispose(IntPtr _handle)
    {
        handle = _handle;
    }

    /// <summary>
    /// 开始释放
    /// </summary>
    public void Dispose()
    {
        Dispose(true);
        // Take yourself off the Finalization queue 
        // to prevent finalization code for this object
        // from executing a second time.
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                // 释放控制的资源
                Components.Dispose();
            }
            CloseHandle(handle);
            handle = IntPtr.Zero;
        }
        disposed = true;
    }

    //在“垃圾回收”回收 System.Object 之前尝试释放资源并执行其他清理操作
    ~PDispose()
    {
        // Do not re-create Dispose clean-up code here.
        // Calling Dispose(false) is optimal in terms of
        // readability and maintainability.
        Dispose(false);
    }

    //使用系统组件清除对象句柄
    [System.Runtime.InteropServices.DllImport("Kernel32")]
    private extern static Boolean CloseHandle(IntPtr handle);

}
